using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class JobSeekers_JobResults : System.Web.UI.Page
{
    string typeName = "";
    string typeID = "";
    string typeValue = "";
    string typeUrl = "";
    string connectionString = "";
    int itemPerPage = 15;
    int pagePerSeggment = 5;

    void RegisterJavaScript()
    {
        Common common = new Common();
        ClientScript.RegisterClientScriptBlock(
        this.GetType(), "openWindow" + 
        this.GridView1.ID, 
        common.CreateScriptForPrint(this.GridView1.ID));
        btnPrint.Attributes.Add("onclick", 
        "openWindow" + this.GridView1.ID 
        + "('" + GridView1.ID.ToString() 
        + "',400,700);return false;");	
        
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        connectionString =
         WebConfigurationManager.ConnectionStrings[
           "RecruitVietnam"].ConnectionString;

        RegisterJavaScript();
        if(!IsPostBack)
        {
            ViewState["SortDirection"] = "ASC";
            typeID = Request.QueryString.Get("ID");
            typeName = Request.QueryString.Get("type");
            typeValue = Request.QueryString.Get("value");
            typeUrl = Request.QueryString.Get("page");
            this.btnBack.Attributes.Add("onclick", 
            "window.open('" + typeUrl + 
            "', target='_main');return false;");
            if (typeID != null && typeID != "")
            {
                litID.Text = typeID;
                litValue.Text = typeValue;
                litType.Text = typeName;
                litUrl.Text = typeUrl;
                ShowResult(typeID, typeName, 0);             
            }
        }
        else
        {
            typeID = litID.Text;
            typeName = litType.Text;
            typeValue = litValue.Text;
            typeUrl = litUrl.Text;
        }
        if (typeID == "" || typeID == null 
        || typeName == "" || typeName == null)
            Response.Redirect("search.aspx");
        CreateNavigation(Convert.ToInt32(
       literalPages.Text), Convert.ToInt32(
       literalCurrentPage.Text), itemPerPage,
       pagePerSeggment, this.panelNavigation);
    }
    
    void CreateNavigation(
    int totalPages, int currentPage,
    int itemPerPage, int pagePerSeggent,
    Panel panelLinks)
    {
        panelLinks.Controls.Clear();
        int startPageNo = 0; int endPageNo = 0; int seggmentNo = 0;
        if (totalPages > 1)
        {
            seggmentNo = currentPage / pagePerSeggent;
            if ((currentPage % pagePerSeggent) > 0) seggmentNo += 1;
            startPageNo = pagePerSeggent * (seggmentNo - 1) + 1;
            if (seggmentNo * pagePerSeggent > totalPages)
                endPageNo = totalPages;
            else
                endPageNo = seggmentNo * pagePerSeggent;


            LinkButton linkButton;
            Label labelSpace;

            if (seggmentNo > 1)
            {
                linkButton = new LinkButton();
                linkButton.Text = "First";
                linkButton.Click += new EventHandler(linkButton_Click);
                linkButton.ID = (1).ToString();
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }

            if (currentPage > pagePerSeggent)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Previous";
                linkButton.Click += new EventHandler(linkButton_Click);
                linkButton.ID = (startPageNo - 1).ToString();
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            int i = 0;
            for (i = startPageNo; i <= endPageNo; i++)
            {
                linkButton = new LinkButton();
                linkButton.Text = i.ToString();

                linkButton.ID = i.ToString();
                if (i  == currentPage)
                    linkButton.BackColor = System.Drawing.Color.Aqua;
                linkButton.Click += new EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            if (seggmentNo * pagePerSeggent < totalPages)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Next";
                linkButton.ID = (i).ToString();
                linkButton.Click += new EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            if (seggmentNo * pagePerSeggent + 1 < totalPages)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Last";
                linkButton.ID = totalPages.ToString();
                linkButton.Click += new EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp;";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
        }
    }
    void linkButton_Click(object sender, EventArgs e)
    {        

        LinkButton linkButton = (LinkButton)sender;

        int nextPage = 0;
        nextPage = Convert.ToInt32(linkButton.ID);
        literalCurrentPage.Text = nextPage.ToString();
        int endJobs = nextPage * 
        Convert.ToInt32(itemPerPage);
        if (endJobs > Convert.ToInt32(
        literalTotal.Text)) 
        endJobs = Convert.ToInt32(literalTotal.Text);
        literalRecords.Text = 
        " - Display job: " + 
        (nextPage - 1) * itemPerPage + 
        " -> " + endJobs.ToString();

        ShowResult(typeID, typeName, nextPage - 1);
         

    }
    DataTable GetDataTable(string typeID, string typeName, int firstRecord)
    {
        SqlServerProvider sqlServerProvider = 
        new SqlServerProvider();
        sqlServerProvider.ConnectionString = 
        connectionString;
        
        sqlServerProvider.ParameterCollection = 
        new string[2] { "@TypeID", "@TypeName" };
        sqlServerProvider.ValueCollection = 
        new string[2] { typeID, typeName };
        sqlServerProvider.CommandType = 
        CommandType.StoredProcedure;
        if (firstRecord == 0)
        {
            sqlServerProvider.CommandText = "SPTotalJobList";
            literalTotal.Text = sqlServerProvider.ExecuteScalar().ToString();
            ShowTotalPages(Convert.ToInt32(literalTotal.Text));
        }
        sqlServerProvider.CommandText =
        "SPJobList";
        DataTable dataTable = 
        sqlServerProvider.GetDataTable(
        firstRecord * itemPerPage, itemPerPage);
        return dataTable;
    }
    void ShowTotalPages(int totalRecords)
    {

        int totalPages = totalRecords / itemPerPage;
        if (totalRecords % itemPerPage != 0)
            totalPages++;
        literalPages.Text = totalPages.ToString();
    }
    DataView GetDataView(string typeID, string typeName, string columnName, string sortType, int firstRecord)
    {
        SqlServerProvider sqlServerProvider = new SqlServerProvider();
        sqlServerProvider.ConnectionString = connectionString;
        sqlServerProvider.CommandText =
        "SPJobList";
        sqlServerProvider.ParameterCollection = new string[2] { "@TypeID", "@TypeName" };
        sqlServerProvider.ValueCollection = new string[2] { typeID, typeName };
        sqlServerProvider.CommandType = CommandType.StoredProcedure;
        DataTable dataTable = sqlServerProvider.GetDataTable(firstRecord * itemPerPage, itemPerPage);
        DataView dataView = new DataView(dataTable);
        dataView.Sort = columnName + " " + sortType;
        return dataView;
    }
    void ShowHide(bool flag)
    {
        literalTotal.Visible = flag;
        literalCurrentPage.Visible = flag;
        literalOfText.Visible = flag;
        literalPageText.Visible = flag;
        literalTotalText.Visible = flag;
        literalRecords.Visible = flag;
        literalPages.Visible = flag;
    }
    void ShowResult(string typeID, string typeName, int firstRecord)
    {
        try{
            GridViewHelper gridViewHelper = new GridViewHelper();
            gridViewHelper.FillDataTableToGridView(
            GetDataTable(typeID, typeName, firstRecord),
            this.GridView1); ;
            FillUrl(this.GridView1, typeUrl);
            if (GridView1.Rows.Count == 0)
                {
                    litError.Text = "Job not found.";
                    ShowHide(false);
                }
            else
                {
                    ShowHide(true);
                     
                litError.Text = "";
                int currentRecords = Convert.ToInt32(literalCurrentPage.Text);
                litError.Text = "";
                literalRecords.Text =
                " - Display job: " +
                ((currentRecords - 1) * itemPerPage + 1).ToString()
                + "-";
                if ((currentRecords - 1) * itemPerPage + itemPerPage < Convert.ToInt32(literalTotal.Text))
                    literalRecords.Text +=
                    ((currentRecords - 1) * itemPerPage +
                    itemPerPage).ToString();
                else
                    literalRecords.Text += literalTotal.Text;
                literalRecords.Text += " of " + literalTotal.Text;
                }
                CreateNavigation(Convert.ToInt32(
                           literalPages.Text), Convert.ToInt32(
                           literalCurrentPage.Text), itemPerPage,
                           pagePerSeggment, this.panelNavigation);
        }
        catch(Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    void ShowResult(string typeID, string typeName, string columnName, string sortType, int firstRecord)
    {
        try
        {
            GridViewHelper gridViewHelper = new GridViewHelper();
            gridViewHelper.FillDataViewToGridView(
            GetDataView(typeID, typeName, columnName, sortType, firstRecord),
            this.GridView1); ;
            FillUrl(this.GridView1, typeUrl);
            if (GridView1.Rows.Count == 0)
                litError.Text = "Job not found.";
            else
                litError.Text = "";
        }
        catch (Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    void FillUrl(GridView GridView1, string backUrl)
    {
        foreach(GridViewRow gridViewRow in GridView1.Rows)
        {
            HyperLink  hyperLinkField =
            (HyperLink )gridViewRow.Cells[1].Controls[0];
            hyperLinkField.NavigateUrl =
           hyperLinkField.NavigateUrl + "&page=" + backUrl;
        }
    }
     


    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        ShowResult(typeID, typeName, e.SortExpression, 
        ViewState["SortDirection"].ToString(), 
        Convert.ToInt32(literalCurrentPage.Text) - 1);
        if (ViewState["SortDirection"].ToString() == "ASC")
            ViewState["SortDirection"] = "DESC";
        else
            ViewState["SortDirection"] = "ASC";
    }
}
